//
//  DnpNet.m
//  dnp_plugin
//
//

#import "DnpNet.h"

#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <SystemConfiguration/SCNetworkReachability.h>

@implementation DnpNet

+ (NSString *)finger {
    struct sockaddr_storage storage = {0};
    storage.ss_len = sizeof(storage);
    storage.ss_family = AF_INET;
    
    SCNetworkReachabilityRef reachabilityRef = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&storage);
    if (!reachabilityRef) {
        return @"OTHER";
    }
    
    SCNetworkReachabilityFlags reachabilityFlags;
    BOOL resultFlags = SCNetworkReachabilityGetFlags(reachabilityRef, &reachabilityFlags);
    CFRelease(reachabilityRef);
    
    if (!resultFlags) {
        return @"OTHER";
    }
    
    BOOL isReachable = (reachabilityFlags & kSCNetworkFlagsReachable);
    BOOL connectionRequired = (reachabilityFlags & kSCNetworkFlagsConnectionRequired);
    
    if (!isReachable || connectionRequired) {
        return @"OTHER";
    }
    
    if (reachabilityFlags & kSCNetworkReachabilityFlagsIsWWAN) {
        return [self getFingerType];
    } else {
        return @"WIFI";
    }
}

+ (NSString *)getFingerType {
    CTTelephonyNetworkInfo *networkInfo = [[CTTelephonyNetworkInfo alloc] init];
    if (!networkInfo) {
        return @"OTHER";
    }
    
    NSString *tech = nil;
    
    if ([networkInfo respondsToSelector:@selector(serviceCurrentRadioAccessTechnology)]) {
        NSDictionary *radioTech = [networkInfo serviceCurrentRadioAccessTechnology];
        tech = radioTech.allValues.firstObject;
    }
    
    if (!tech) {
        return @"OTHER";
    }
    
    NSDictionary *techMapping = @{
        CTRadioAccessTechnologyLTE: @"4G",
        CTRadioAccessTechnologyWCDMA: @"3G",
        CTRadioAccessTechnologyHSDPA: @"3G",
        CTRadioAccessTechnologyHSUPA: @"3G",
        CTRadioAccessTechnologyCDMAEVDORev0: @"3G",
        CTRadioAccessTechnologyCDMAEVDORevA: @"3G",
        CTRadioAccessTechnologyCDMAEVDORevB: @"3G",
        CTRadioAccessTechnologyeHRPD: @"3G",
        CTRadioAccessTechnologyEdge: @"2G",
        CTRadioAccessTechnologyGPRS: @"2G",
        CTRadioAccessTechnologyCDMA1x: @"2G"
    };
    
    if (@available(iOS 14.1, *)) {
        NSMutableDictionary *mutableMapping = [techMapping mutableCopy];
        mutableMapping[CTRadioAccessTechnologyNRNSA] = @"5G";
        mutableMapping[CTRadioAccessTechnologyNR] = @"5G";
        techMapping = [mutableMapping copy];
    }
    
    return techMapping[tech] ?: @"OTHER";
}

@end
